//
//  HZKeyChain.m
//  HZTC_YaDeArt
//
//  Created by MayerF on 17/3/25.
//  Copyright © 2017年 HZTC. All rights reserved.
//

#import "HZKeyChain.h"
#import <Security/Security.h>

@implementation HZKeyChain

+ (NSMutableDictionary *)configkeychain:(NSString *)keyName {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (id)kSecClassGenericPassword,(id)kSecClass,
            keyName, (id)kSecAttrService,
            keyName, (id)kSecAttrAccount,
            nil];
}

+ (BOOL)keyChainSaveData:(id)data keyName:(NSString *)keyName
{
    NSMutableDictionary *keychainConfig = [self configkeychain:keyName];
    SecItemDelete((CFDictionaryRef)keychainConfig);
    [keychainConfig setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
    OSStatus status = SecItemAdd((CFDictionaryRef)keychainConfig, NULL);
    if (status == errSecSuccess) {
        return YES;
    }
    return NO;
}

+ (id)keyChainReadKeyName:(NSString *)keyName
{
    id ret = nil;
    NSMutableDictionary *keychainConfig = [self configkeychain:keyName];
    [keychainConfig setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    [keychainConfig setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    CFDataRef result = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)keychainConfig, (CFTypeRef *)&result) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)result];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", keyName, e);
        } @finally {
        }
    }
    if (result)
        CFRelease(result);
    return ret;
}

+ (BOOL)keyChainDeletekeyName:(NSString *)keyName
{
    BOOL isSuccess = NO;
    NSMutableDictionary *keychainConfig = [self configkeychain:keyName];
    OSStatus status = SecItemDelete((CFDictionaryRef)keychainConfig);
    if (status == errSecSuccess) {
        isSuccess = YES;
    }
    return isSuccess;
}

@end
